<?php
namespace app\admin\controller;

use app\BaseController;
use app\common\model\StaffModel;

use app\common\model\StaffProfileModel;
use app\common\model\StaffManageModel;

use app\common\model\FirmModel;
use ZipArchive;
use PhpOffice\PhpSpreadsheet\IOFactory;
use app\common\OpenApi;
class Staff extends BaseController{
    //员工列表
    public function list(){
        $keyword = $this->request->param('keyword/s','');
        $division_id = $this->request->param('division_id/d',0);//部门ID
        $where=[
            ['is_delete','=',0],
            ['firm_id','=',$this->request->firm_id]
        ];
        if(!empty($division_id)){
            $where[] = ['division_id','=',$division_id];
        }
        if(!empty($keyword)){
            $where[] = ['name|position|mobile|notes','LIKE','%'.$keyword.'%'];
        }

        $list = StaffModel::where($where)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->order(['sort'=>'desc','staff_id'=>'desc'])
            ->select();

        $total = StaffModel::where($where)->count('staff_id');
        // return success($total);
        return success([
            'list' => $list,
            'total' => $total
        ]);
    }
    //员工详情
    public  function detail(){
        $staff_id = $this->request->param('staff_id/d',0);
        if(empty($staff_id)){
            return error('错误操作');
        }
        if(null === $staff = StaffModel::with(['detail','profile'])->find($staff_id)){
            return error('员工不存在');
        }
        if($staff->firm_id != $this->request->firm_id){
             return error('无权限');
        }
        return success($staff);
    }
    // //保存员工信息
    public function save(){
        $staff_id = $this->request->param('staff_id/d',0);

        $name = $this->request->param('name/s','');
        $mobile  = $this->request->param('mobile/s','');
        $position = $this->request->param('position/s','');
        $sort = $this->request->param('sort/d',0);
        $status = $this->request->param('status/d',1);
        $notes = $this->request->param('notes/s','');
        
        $bind_code = $this->request->param('bind_code/d',0);

        $name_en = $this->request->param('name_en/s','');
        $position_en = $this->request->param('position_en/s','');
        $weixin  = $this->request->param('weixin/s','');
        $wx_qr  = $this->request->param('wx_qr/s','');
        $mail  = $this->request->param('mail/s','');
        $spare1 = $this->request->param('spare1/s','');
        $spare2 = $this->request->param('spare2/s','');
        $is_card  = $this->request->param('is_card/d',0);
        $card  = $this->request->param('card/s','');
        $face    = $this->request->param('face/s','');
        $tag = $this->request->param('tag/a',[]);
        $is_share  = $this->request->param('is_share/d',0);
        $share_text = $this->request->param('share_text/s','');
        $share_image = $this->request->param('share_image/s','');
        
        $profile_type = $this->request->param('profile_type/s','text');
        $profile_text = $this->request->param('profile_text/s','');

        if(empty($name)){
            return error('请填写员工姓名');
        }
        if(empty($staff_id)){
            $staff = new StaffModel();
            $staff->firm_id = $this->request->firm_id;
            $staff->code = substr(time(),1,9).mt_rand(1000000, 9999999);
        }else{
            if(null === $staff = StaffModel::find($staff_id)){
                return error('请选择要编辑的内容');
            }
            if($staff->shop_id != $this->request->shopId){
                 return error('请选择要编辑的内容');
            }
        }
        $staff->name = $name;
        $staff->mobile = $mobile;
        $staff->position = $position;
        $staff->sort = $sort;
        $staff->status = $status;
        $staff->notes = $notes;
        if($this->request->role > 5){
            $staff->bind_code = $bind_code;
        }
        $staff->save();
        
        if(empty($staff_id)){
            $staffDetail = [
                'name_en' => $name_en,
                'position_en' => $position_en,
                'weixin' => $weixin,
                'wx_qr' => $wx_qr,
                'mail' => $mail,
                'spare1' => $spare1,
                'spare2' => $spare2,
                'card' => $card,
                'is_card' => $is_card,
                'face' => $face,
                'tag' => $tag,
                'is_share' => $is_share,
                'share_image' => $share_image,
                'share_text' => $share_text
            ];
            $staff->detail()->save($staffDetail);
            $staffProfile = [
                'profile_type' => $profile_type,
                'profile_text' => $profile_text
            ];
            
            $staff->profile()->save($staffProfile);
        }else{
           $staff->detail->name_en = $name_en;
           $staff->detail->position_en = $position_en;
           $staff->detail->weixin = $weixin;
           $staff->detail->wx_qr = $wx_qr;
           $staff->detail->mail = $mail;
           $staff->detail->spare1 = $spare1;
           $staff->detail->spare2 = $spare2;
           $staff->detail->card = $card;
           $staff->detail->is_card = $is_card;
           $staff->detail->face = $face;
           $staff->detail->tag = $tag;
           $staff->detail->is_share = $is_share;
           $staff->detail->share_image = $share_image;
           $staff->detail->share_text = $share_text;
           $staff->detail->save();
           if(null === $StaffProfileModel = StaffProfileModel::find($staff_id)){
                $staffProfile = [
                    'profile_type' => $profile_type,
                    'profile_text' => $profile_text
                ];
                
                $staff->profile()->save($staffProfile);
            }else{
                $staff->profile->profile_type = $profile_type;
                $staff->profile->profile_text = $profile_text;
                $staff->profile->save();
            }
           
        }
        
        return success('保存成功');
    }
    public function profile(){
        $staff_id = $this->request->param('staff_id/d');
        if(empty($staff_id)){
            return error('错误操作');
        }
        if(null === $StaffModel = StaffModel::with(['custom'])->find($staff_id)){
            return null;
        }
        // if($StaffModel->firm_id != $this->request->firm_id){
        //      return error('无权限');
        // }
        return success($StaffModel);
    }

    // //保存员工简介
    public function profileSave(){
        $staff_id = $this->request->param('staff_id/d');
        $profile_custom = $this->request->param('profile_custom/s',[]);
        $profile_custom = json_decode($profile_custom,true);
        if(empty($staff_id)){
            return error('错误操作');
        }
        if(null === $StaffProfileModel = StaffProfileModel::find($staff_id)){
            $StaffProfileModel = new StaffProfileModel();
            $StaffProfileModel->staff_id = $staff_id;
        }
        $StaffProfileModel->profile_custom = $profile_custom;
        $StaffProfileModel->save();
        return success($StaffProfileModel);
    }
    
    public function delete(){
        $staff_id = $this->request->param('staff_id/d',0);
        if(empty($staff_id)){
            return error('错误操作');
        }
        if(null === $staff = StaffModel::find($staff_id)){
            return error('员工不存在');
        }
        if($staff->firm_id != $this->request->firm_id){
             return error('无权限');
        }
        $staff->is_delete = 1;
        $staff->save();
        return success('删除成功');
    }
    
    //批量导入
    public function saveExcel(){
        if(empty($_FILES['file'])){
            return error('请选择导入的文件');
        }
        try{
            $objPHPExcel = IOFactory::load($_FILES['file']['tmp_name']);
            $sheet = $objPHPExcel->getActiveSheet();
            $success = 0;
            $error = 0;
            foreach ($sheet->getRowIterator() as $key => $row) {
                if($key == 1){
                    continue;
                }
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $staff = new StaffModel();
                $staff->firm_id = $this->request->firm_id;
                $staff->code = substr(time(),1,9).mt_rand(1000000, 9999999);
                $rowData = [];
                foreach ($cellIterator as $k=>$cell) {
                    $param = $cell->getValue();
                    if($param != null){
                        $param = trim($param);
                    }
                    if($k == 'B'){
                        $staff->name = $param;
                    }
                    if($k == 'F'){
                        $staff->mobile = $param;
                    }
                    if($k == 'D'){
                        $staff->position = $param;
                    }
                    if($k == 'C'){
                        $rowData['name_en'] = $param;
                    }
                    if($k == 'E'){
                        $rowData['position_en'] = $param;
                    }
                    if($k == 'G'){
                        $rowData['weixin'] = $param;
                    }
                    if($k == 'H'){
                        $rowData['mail'] = $param;
                    }
                    if($k == 'I'){
                        $rowData['spare1'] = $param;
                    }
                    if($k == 'J'){
                        $rowData['spare2'] = $param;
                    }
                }
                if($staff->save() && $staff->detail()->save($rowData) && $staff->profile()->save([])){
                    $success++;
                }else{
                    $error++;
                }
            }
            return success(['success'=>$success,'error'=>$error]);
        }catch(Exception $e){
            return error($e);
        }
        
        
    }
    
    public function getShareQRCode(){//获取分享二维码
        $code = $this->request->param('code/d',0);
        if($code === 0){
            return error('参数错误');
        }
        $dir = root_path().'/public';
        $path = '/upload/qr/'.$this->request->firm_id.'/share/';
        !is_dir($dir.$path) && mkdir($dir.$path, 0755, true);
        
        $firm_info = FirmModel::find($this->request->firm_id);
        
        $firm_id = $firm_info->parent_id;
        
        //未设置小程序
        // if($firm_info->type === 0 || $firm_info->secret_key === 0){
        //     $firm_id = 11;
        // }else{
        //     $firm_id = $this->request->firm_id;
        // }
        
        //  //已绑定其他账号
        // if($firm_info->parent_id > 0){
        //     $firm_id = $firm_info->parent_id;
        // }
        
        $path = $path.$firm_id.'_'.$code.'.png';
        
        if(!file_exists($dir.$path)){
            $data = ['code' => $code];
            $OpenApi = new OpenApi($firm_id);
            $res = $OpenApi->openApiPostImage('miniapp/getShareQrCode',$data);
            file_put_contents($dir.$path, $res);
        }
        return success(['qr_url'=>'https://'.$_SERVER['SERVER_NAME'].$path]);
    }
    
    public function export()
    {
        $staffList=StaffModel::field('staff_id,name,code')->where('firm_id',$this->request->firm_id)->select();
        
        $firm_info = FirmModel::find($this->request->firm_id);
        $firm_id = $firm_info->parent_id;
        $dir = root_path().'/public';
        
        $path = '/upload/qr/'.$this->request->firm_id.'/share/';
        
        !is_dir($dir.$path) && mkdir($dir.$path, 0755, true);
        
        // //未设置小程序
        // if($firm_info->type === 0 || $firm_info->secret_key === 0){
        //     $firm_id = 11;
        // }else{
        //     $firm_id = $this->request->firm_id;
        // }
        //  //已绑定其他账号
        // if($firm_info->parent_id > 0){
        //     $firm_id = $firm_info->parent_id;
        // }
        $zip = new ZipArchive();
        $zipName = $dir.$path.date('YmdHis').'.zip';
        $zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
        $OpenApi = new OpenApi($firm_id);
        if(empty(!$staffList)){
            foreach ($staffList as $k => $v){
                $filename = 'share_'.$firm_id.'_'.$this->request->firm_id.'_'.$v['code'].'.png';
                $filePath = $dir.$path.$filename;
                if(!file_exists($filePath)){
                    $data = ['code' => $v['code']];
                    $res = $OpenApi->openApiPostImage('miniapp/getShareQrCode',$data);
                    file_put_contents($filePath, $res);
                }
                $zip->addFile($filePath,$v['name'].'.png');
            }
        }
        $zip->close();
        //这里是下载zip文件
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: " . filesize($zipName));
        header("Content-Disposition: attachment; filename=\"" . basename($zipName) . "\"");
        readfile($zipName);
        exit;
    }
    
    public function bindCode(){
        $where=[
            ['is_delete','=',0],
            ['firm_id','=',$this->request->firm_id]
        ];
        $list = StaffModel::where($where)->select();
        $success = 0;
        $error = 0;
        foreach ($list as $key => $item){
            if($item['mobile']){
                $count = StaffManageModel::where([
                    'bind_mobile' => $item['mobile'],
                    'user_id' => 0,
                    'is_delete' => 0
                ])->count('staff_manage_id');
                
                if($count){
                    $error++;
                }else{
                    $StaffManageModel = new StaffManageModel();
                    $StaffManageModel->staff_id = $item['staff_id'];
                    $StaffManageModel->bind_mobile = $item['mobile'];
                    $StaffManageModel->save();
                    $success++; 
                }
                
            }else{
                $error++;
            }
        }
        return success(['success'=>$success,'error'=>$error]);
    }
    public function manageSave(){
        $staff_manage_id = $this->request->param('staff_manage_id/d',0);
        $staff_id = $this->request->param('staff_id/d',0);
        if($staff_manage_id > 0){
            if(null === $StaffManageModel = StaffManageModel::find($staff_manage_id)){
                return error('删除失败');
            }
            $StaffManageModel->is_delete = 1;
            $StaffManageModel->save();
            return success('删除成功');
            
        }else{
            $mobile = StaffModel::where('staff_id',$staff_id)->value('mobile');
            if($mobile){
                $count = StaffManageModel::where([
                    'bind_mobile' => $mobile,
                    'user_id' => 0,
                    'is_delete' => 0
                ])->count('staff_manage_id');
                if($count){
                    return error('该员工手机号码存在未绑定记录，请先绑定后再重新创建');
                }
                $StaffManageModel = new StaffManageModel();
                $StaffManageModel->staff_id = $staff_id;
                $StaffManageModel->bind_mobile = $mobile;
                $StaffManageModel->save();
                return success('添加成功');
            }else{
                return error('请先设置员工手机号');
            }
            
        }
    }
    
    public function manageList(){
        $staff_id = $this->request->param('staff_id/d',0);
        if($staff_id === 0){
            return error('参数错误');
        }
        // $list = StaffManageModel::where('staff_id',$staff_id)->select();
        $where = [
            ['staff_id','=',$staff_id],
            ['is_delete','=',0],
        ];
        $list = StaffManageModel::where($where)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->order('staff_manage_id', 'desc')
            ->select()->append(['user']);

        $total = StaffManageModel::where($where)->count('staff_manage_id');
        // return success($total);
        return success([
            'list' => $list,
            'total' => $total
        ]);
    }
}